<template>
    <div class="app-container">
        <el-form style="margin-bottom: 10px;" class="formList" :model="queryParams" ref="queryForm" :inline="true"
            v-show="showSearch" label-width="100px" size="small">
            <el-row>
                <el-form-item label="时间">
                    <el-date-picker @change="getList" v-model="queryParams.times" type="year" value-format="yyyy"
                        placeholder="时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item style="margin-left: 22px">
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-row>
        </el-form>

        <div class="divTable">
            <el-table border v-loading="loading" :data="brandList" @selection-change="handleSelectionChange">
                <el-table-column label="月份" align="center" prop="month" />
                <el-table-column sortable label="注册人数" align="center" prop="count">
                    <template slot-scope="scope">
                        <a v-if="scope.row.count > 0" style="color: #1890ff;" @click="handledetail(scope.row, 'zuce')">{{
                            scope.row.count }}
                        </a>
                        <span v-else>{{ scope.row.count }}</span>

                    </template>
                </el-table-column>
                <el-table-column label="下单人数" align="center" prop="orderCount">
                    <template slot-scope="scope">
                        <a v-if="scope.row.orderCount > 0" style="color: #1890ff;"
                            @click="handledetail(scope.row, 'xiadan')">{{ scope.row.orderCount }}
                        </a>
                        <span v-else>{{ scope.row.orderCount }}</span>

                    </template>
                </el-table-column>
                <el-table-column sortable label="转换率" align="center" prop="countProportionStr" />
                <!-- <el-table-column label="销售金额占比" align="center" prop="amountProportion" />
              <el-table-column label="操作" align="center" prop="createTime">
                  <template slot-scope="scope">
                      <el-button type="text" size="mini" icon="el-icon-zoom-in"
                          @click="handlee(scope.row)">详情</el-button>
                  </template>
              </el-table-column> -->

            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>



        <el-dialog title="详情" :visible.sync="dialogVisible" width="50%">
            <el-table border :data="list">
                <el-table-column label="客户姓名" align="center" prop="customerName" />
                <el-table-column label="性别" align="center" prop="sexType" />
                <el-table-column label="手机号" align="center" prop="phone" />
                <el-table-column label="日期" align="center" prop="createTime" />
            </el-table>
            <!-- <el-table border :data="list" v-if="type != 'zuce'">
                <el-table-column label="订单编号" align="center" prop="orderNo" />
                <el-table-column label="客户姓名" align="center" prop="customerName" />
                <el-table-column label="手机号" align="center" prop="phone" />
                <el-table-column label="购买门店" align="center" prop="storeName" />
                <el-table-column label="现金" align="center" prop="payAmountStr" />
                <el-table-column label="金币" align="center" prop="payByBalanceStr" />
                <el-table-column label="银币" align="center" prop="payByRedBagStr" />
                <el-table-column label="日期" align="center" prop="payTime" />
            </el-table> -->
            <pagination v-show="totalQuery > 0" :total="totalQuery" :page.sync="query.pageNum" :limit.sync="query.pageSize"
                @pagination="getListDetail" />
        </el-dialog>



    </div>
</template>

<script>

import {
    selectGroup
} from "@/api/platform/store"


import {
    listInfo
} from "@/api/order/info"


import {
    selectRegistrationConversion, getCustomerInfoDetail,getCustomerInfoOrderDetail
} from "@/api/statistics/statistics";


import { onInput } from "@/utils/util";
export default {
    name: "Brand",
    components: {

    },
    data() {
        return {
            listData: {},
            list: [],
            totalQuery: 0,
            dialogVisible: false,
            query: {
                pageSize: 10,
                pageNum: 1,
                type: '',
                userId: '',
                time: '',
                createTimeArray: [],
                orderStatus: 1,
                payStatus: 1
            },
            selectedDataCopy: [{}],
            selectedData: [],
            storeOpen: false,
            selectedDataStore: {},
            couponOpen: false,
            selectedDataCoupon: {},
            cardAOpen: false,
            selectedDataCard: {},
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            //选中数组的名字
            names: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 储值/系列表格数据
            brandList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            openA: false,
            // 用于类别关联的分类显示
            dialogVisible: false,
            //常用状态数据字典
            statusOptions: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                customerName: null,
                phone: null,
                startTime: null,
                endTime: null,
                applyAuthTimeArray: [],
                receiveCustomerName: null,
                receiveCustomerPhone: null,
                receiveStatus: null,
                nickName: null,
                name: null,
                storeId: null,
                time: null,
                times: null,
            },
            // 商品
            productOpen: false,
            selectedDataProduct: {},



            options: [
                {
                    value: "1",
                    label: "已领取",
                },
                {
                    value: "0",
                    label: "未领取",
                },
            ],
            // 表单参数
            form: {
                customerName: null,
                phone: "",
                dataPriority: "",
                isDataValue: "",
                rightType: "",
            },
            storeInFoOptions: [],
            // 表单校验
            rules: {
                rechargeName: [
                    {
                        required: true,
                        message: "储值名称不能为空",
                        trigger: "blur",
                    },
                ],
                isDataValue: [
                    {
                        required: true,
                        message: "储值属性不能为空",
                        trigger: "change",
                    },
                ],
                rightType: [
                    {
                        required: true,
                        message: "储值权益不能为空",
                        trigger: "change",
                    },
                ],
            },
            defaultProps: {
                children: "children",
                label: "label",
            },
            type: "",
        };
    },
    created() {
        let date = new Date();
        this.queryParams.times = date.getFullYear() + ""
        this.queryParams.time = date.getFullYear() + "-";
        console.log(this.queryParams)
        this.getList();
        // this.getDicts("sys_data_status").then((response) => {
        //     this.statusOptions = response.data;
        // });
        // selectGroup().then(response => {
        //     this.storeInFoOptions = response.data || [];
        // });
    },
    watch: {

    },
    methods: {
        handledetail(row, type) {
            this.type = type;
            this.query.time = row.month;
            // /**
            //  * 处理时间
            //  */
            // let dateArr = row.month.split("-");
            // var lastDay = new Date(dateArr[0], dateArr[1], 0);
            // var month = lastDay.getMonth() + 1;
            // month = month < 10 ? '0' + month : month;
            // var day = lastDay.getDate();
            // day = day < 10 ? '0' + day : day;

            // this.query.createTimeArray = [];
            // this.query.createTimeArray.push(row.month + "-01")
            // this.query.createTimeArray.push(row.month + "-" + day)
            this.getListDetail();
        },
        onInput,
        handlee(row) {
            this.query.userId = row.userId
            this.getListDetail();
        },
        tabResponCard() {
            this.selectedDataCard = {};
        },
        tabResponCoupon() {
            this.selectedDataCoupon = {};
        },
        tabRespon() {
            this.selectedDataStore = {};
        },
        tabResponProduct() {
            this.selectedDataProduct = {};
        },
        dataPriorityInput(value) {
            let js = value + "";
            return js.replace(/^(0+)|[^\d]+/g, "");
        },
        /** 查询储值/系列列表 */

        getListDetail() {

            if (this.type == 'zuce') {

                getCustomerInfoDetail(this.query).then(response => {

                    this.list = response.rows
                    this.totalQuery = response.total;
                    this.dialogVisible = true;
                })

            } else {
                getCustomerInfoOrderDetail(this.query).then(response => {

                    this.list = response.rows
                    this.totalQuery = response.total;
                    this.dialogVisible = true;
                })
            }

        },
        getList() {
            this.queryParams.time = this.queryParams.times + "-";
            this.loading = true;
            selectRegistrationConversion(this.queryParams).then((response) => {
                this.brandList = response.data;
                //   this.listData = response.data;
                // this.total = response.total;
                this.loading = false;
            });
        },

        p(s) {
            return s < 10 ? "0" + s : s;
        },

        selectCommodityCoupon() {
            this.$forceUpdate();
            this.couponOpen = true;
            console.log(this.couponOpen);
            // this.$nextTick(() => {
            //   this.$refs["selTableCoupon"].greet(this.selectedDataCoupon);
            // });
        },

        //调用子组件中方法，向子组件传值
        selectCommodity() {
            this.$forceUpdate();
            this.openA = true;
            this.$nextTick(() => {
                this.$refs["selTable"].greet(this.selectedData);
            });
        },

        selectCommodityCard() {
            this.$forceUpdate();
            this.cardAOpen = true;
            this.$nextTick(() => {
                this.$refs["selTableCard"].greet(this.selectedDataCard);
            });
        },

        selectCommodityProduct() {
            this.productOpen = true;
            this.$nextTick(() => {
                this.$refs["selTableProduct"].greet(this.selectedDataProduct);
            });
        },

        multipleSelection(data) {
            this.openA = false;
            this.selectedData = data;
            // this.$nextTick(() => {
            //   this.$refs.child.getList();
            // });
        },

        selectCommodityService() {
            this.$forceUpdate();
            this.storeOpen = true;
            // this.$nextTick(() => {
            //   this.$refs["selTable"].greet(this.selectedDataStore);
            // });
        },

        toCloseBoxCoupon() {
            this.couponOpen = false;
        },

        toCloseBoxCard() {
            this.cardAOpen = false;
        },

        toCloseBoxProduct() {
            this.productOpen = false;
        },

        toCloseBoxStore() {
            this.storeOpen = false;
        },

        toCloseBox() {
            this.open = false;
        },

        multipleSelectionCoupon(data) {
            this.couponOpen = false;
            this.selectedDataCoupon = data;
            this.$nextTick(() => {
                this.$refs.childCoupon.getList();
            });
        },

        multipleSelectionStore(data) {
            this.storeOpen = false;
            this.selectedDataStore = data;
            this.$nextTick(() => {
                this.$refs.childStore.getList();
            });
        },

        multipleSelectionCard(data) {
            this.cardAOpen = false;
            this.selectedDataCard = data;
            this.$nextTick(() => {
                this.$refs.childCard.getList();
            });
        },

        multipleSelectionProduct(data) {
            this.productOpen = false;
            this.selectedDataProduct = data;
            this.$nextTick(() => {
                this.$refs.childProduct.getList();
            });
        },

        getSTime(val) {
            //手动赋值，使其通过校验

            const d = new Date(val[0]);
            const resDate =
                d.getFullYear() +
                "-" +
                this.p(d.getMonth() + 1) +
                "-" +
                this.p(d.getDate());
            const resTime =
                this.p(d.getHours()) +
                ":" +
                this.p(d.getMinutes()) +
                ":" +
                this.p(d.getSeconds());
            this.form.startTime = resDate + " " + resTime;
            const c = new Date(val[1]);
            const resDatec =
                c.getFullYear() +
                "-" +
                this.p(c.getMonth() + 1) +
                "-" +
                this.p(c.getDate());
            const resTimec =
                this.p(c.getHours()) +
                ":" +
                this.p(c.getMinutes()) +
                ":" +
                this.p(c.getSeconds());
            this.form.endTime = resDatec + " " + resTimec;
        },

        handleChange(value) {
            console.log(value);
        },

        handleRemove(file, fileList) { },
        handlePictureCardPreviewLogo(file) {
            this.logoUr = file.url;
            this.dialogVisible = true;
        },
        handlePictureCardPreviewImg(file) {
            this.deviceImage = file.url;
            this.dialogVisible = true;
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 关联的取消按钮
        cancelBrand() {
            this.openBrand = false;
            this.reset();
        },
        // 表单重置
        reset() {
            // this.form = {
            //   rechargeName: null,
            //   rechargeIcon: null,
            //   isDataValue: '',
            //   dataPriority: 10,
            //   rightType: ''
            // };
            this.form.rechargeName = null;
            this.form.rechargeIcon = null;
            this.form.isDataValue = "";
            this.form.dataPriority = 10;
            this.form.rightType = "";
            this.resetForm("form");
            if (this.$refs["form"]) {
                this.$refs["form"].resetFields();
            }
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 储值菜单 */
        getMenuTreeselect() {
            menuTreeselect().then((response) => {
                this.menuOptions = response.data;
            });
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.rechargeId);
            this.names = selection.map((item) => item.rechargeName);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
            //用于禁用删除
            if (this.multiple == false) {
                for (var i = 0; i < selection.length; i++) {
                    var element = selection[i];
                    if ("1" === element.dataStatus) {
                        this.multiple = true;
                        break;
                    }
                }
            }
        },
        // 状态修改
        handleStatusChange(row) {
            let text = row.dataStatus === "0" ? "无效" : "有效";
            this.$confirm(
                '确定要把储值名称为"' + row.rechargeName + '"设为' + text + "吗？",
                "警告",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            )
                .then(function () {
                    return updateBrandStatus(row.rechargeId, row.dataStatus);
                })
                .then(() => {
                    this.msgSuccess("操作成功");
                    this.getList();
                })
                .catch(function () {
                    row.dataStatus = row.dataStatus === "0" ? "1" : "0";
                });
        },

        // 状态修改
        handleStatusChangeA(row) {
            let text = row.isRecommend === "0" ? "不推荐" : "推荐";
            this.$confirm(
                '确定要把储值名称为"' + row.rechargeName + '"设为' + text + "吗？",
                "警告",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            )
                .then(function () {
                    return updateBrandStatusA(row.rechargeId, row.isRecommend);
                })
                .then(() => {
                    this.msgSuccess("操作成功");
                    this.getList();
                })
                .catch(function () {
                    row.isRecommend = row.isRecommend === "0" ? "1" : "0";
                });
        },

        /** 新增按钮操作 */
        handleAdd() {
            this.selectedDataCopy = [{}];
            this.reset();
            this.open = true;
            this.title = "添加储值";
        },
        handleSave() {
            this.download('prod-api/statistics/selectProductSaleExport', {
                ...this.queryParams
            }, `门店销售数据.xlsx`)

        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.$router.push("/service/recharge/editData/" + row.rechargeId);

            // this.reset();
            // const rechargeId = row.rechargeId || this.ids;
            // getBrand(rechargeId).then((response) => {
            //   this.form = response.data;
            //   console.log(this.form);
            //   this.selectedDataCopy[0].rechargeMoney = this.form.rechargeMoney;
            //   this.selectedDataCopy[0].goldCoin = this.form.goldCoin;
            //   this.selectedDataCopy[0].silverCoin = this.form.silverCoin;
            //   this.selectedDataCopy[0].score = this.form.score;
            //   this.form.timeValue = [];
            //   this.form.timeValue.push(this.form.startTime || "");
            //   this.form.timeValue.push(this.form.endTime || "");
            //   this.open = true;
            //   this.title = "修改储值";
            // });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs.childs.selectImgs();
            this.form.rechargeMoney = this.selectedDataCopy[0].rechargeMoney;
            this.form.goldCoin = this.selectedDataCopy[0].goldCoin;
            this.form.silverCoin = this.selectedDataCopy[0].silverCoin;
            this.form.score = this.selectedDataCopy[0].score;

            // 选择权益
            if (this.form.rightType == "coupon") {
                // 获取id this.selectedDataCoupon
                this.form.rightObjectId = this.selectedDataCoupon.couponUid;
                if (this.form.rightObjectId == null) {
                    this.msgError("请选择优惠券数据");
                    return;
                }
            } else if (this.form.rightType == "card") {
                // 获取id  this.selectedDataCard
                this.form.rightObjectId = this.selectedDataCard.cardId;
                if (this.form.rightObjectId == null) {
                    this.msgError("请选择套餐卡数据");
                    return;
                }
            } else if (this.form.rightType == "service") {
                // 获取id  this.selectedDataStore
                this.form.rightObjectId = this.selectedDataStore.itemId;
                if (this.form.rightObjectId == null) {
                    this.msgError("请选择服务项目数据");
                    return;
                }
            } else if (this.form.rightType == "product") {
                // 获取id  this.selectedDataProduct
                this.form.rightObjectId = this.selectedDataProduct.productUid;
                if (this.form.rightObjectId == null) {
                    this.msgError("请选择商品数据");
                    return;
                }
            }

            console.log(this.form);
            return
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.rechargeId != null) {
                        updateBrand(this.form).then((response) => {
                            // updateRight(this.form)
                            this.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                            this.selectedDataCard = {};
                            this.selectedDataCoupon = {};
                            this.selectedDataStore = {};
                            this.selectedDataProduct = {};
                        });
                    } else {
                        addBrand(this.form).then((response) => {
                            // form.rightObjectId=
                            // addRight(this.form)
                            this.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                            this.selectedDataCard = {};
                            this.selectedDataCoupon = {};
                            this.selectedDataStore = {};
                            this.selectedDataProduct = {};
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const deviceIds = row.rechargeId || this.ids;
            const names = row.rechargeName || this.names;
            this.$confirm('是否确认删除储值名称为"' + names + '"的储值?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(function () {
                    return delBrand(deviceIds);
                })
                .then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                })
                .catch(() => { });
        },

        /** 导出按钮操作 */
        handleExport() {
            this.download(
                "device/brand/export",
                {
                    ...this.queryParams,
                },
                `商品储值.xlsx`
            );
        },
    },
};
</script>

